//
//  SearchVC.m
//  phmall
//
//  Created by admin on 2017/9/28.
//  Copyright © 2017年 admin. All rights reserved.
//

#import "SearchVC.h"
#import "SearchView.h"
#import "Orderheader.h"
#import "SearchResultVC.h"
#import "SearchSuggestionView.h"
#define KHistorySearchPath [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"PYSearchhistories.plist"]
@interface SearchVC ()<UISearchBarDelegate>{
    UIBarButtonItem *seach;
}
/** 搜索栏 */
@property (nonatomic, weak) UISearchBar *searchBar;
@property (nonatomic, strong) SearchView *searchView;
@property (nonatomic, strong) NSMutableArray *hotArray;
@property (nonatomic, strong) Orderheader *headView;
@property (nonatomic, strong) NSMutableArray *historyArray;
@property (nonatomic, strong) SearchSuggestionView *searchSuggestion;
@end

@implementation SearchVC
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navBarBgAlpha=@"1.0";
    // 改变NavBar顶层View的颜色
    self.navigationController.navigationBar.barTintColor = [UIColor whiteColor];
}
- (void)viewDidLoad {
    [super viewDidLoad];

    [self setUI];
}
#pragma mark- 加载ui
-(void)setUI{
    
    seach=[[UIBarButtonItem alloc]initWithTitle:Localized(@"搜索") style:UIBarButtonItemStyleDone target:self action:@selector(rightBarAction)];
    seach.tintColor=[UIColor blackColor];
    self.navigationItem.rightBarButtonItem = seach;
    
    UIBarButtonItem* leftBar=[[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"返回"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStyleDone target:self action:@selector(leftBarAction)];
    
    self.navigationItem.leftBarButtonItem=leftBar;
    
    // 创建搜索框
    [[UISearchBar appearance] setSearchFieldBackgroundImage:[self searchFieldBackgroundImage] forState:UIControlStateNormal];
    UIImageView *titleView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH-120, 30)];
    titleView.backgroundColor=[UIColor whiteColor];
    titleView.layer.cornerRadius = 5;
    titleView.userInteractionEnabled=YES;
    titleView.image=[UIImage imageNamed:@"搜索背景"];
    titleView.layer.masksToBounds=YES;
    self.navigationItem.titleView = titleView;
    ViewBorderRadius(titleView, 5, 1, [UIColor colorWithHexString:@"#adadad"]);
    
    UISearchBar *searchBar = [[UISearchBar alloc] initWithFrame:titleView.bounds];
    searchBar.placeholder = Localized(@"输入关键词");
    searchBar.backgroundImage = [UIImage imageNamed:@"clearImage"];
    searchBar.delegate = self;
    [titleView addSubview:searchBar];
    [searchBar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.offset(0);
        make.height.offset(30);
        make.centerY.offset(0);
        make.width.offset(SCREEN_WIDTH-120);
    }];
    searchBar.tintColor=[UIColor blueColor];
    self.searchBar = searchBar;
    [self.searchBar setImage:[UIImage imageNamed:@"搜索"] forSearchBarIcon:UISearchBarIconSearch state:UIControlStateNormal];
    UITextField * searchField = [self.searchBar valueForKey:@"_searchField"];
    searchField.font=[UIFont systemFontOfSize:13];
    [searchField setValue:[UIFont boldSystemFontOfSize:13] forKeyPath:@"_placeholderLabel.font"];
    
    __weak typeof(self) weakSelf = self;
    _headView = [[Orderheader alloc]init];
    [self.view addSubview:_headView];
    [_headView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(0);
        make.left.right.equalTo(self.view);
        make.height.offset(40);
    }];
    _headView.backgroundColor=[UIColor colorWithHexString:@"#f8fafd"];
    _headView.itemClickAtIndex = ^(NSInteger index){
        [weakSelf adjustScrollView:index];
    };
    _headView.items = @[Localized(@"搜索商品"),Localized(@"搜索店铺")];
    
    

    self.searchView = [[SearchView alloc] initWithFrame:CGRectZero hotArray:self.hotArray historyArray:self.historyArray];
    //
    //        self.searchView.tableView.delegate=self;
    _searchView.tapAction = ^(NSString *str) {
        [weakSelf pushToSearchResultWithSearchStr:str];
    };
    [self.view addSubview:self.searchView];
    [self.searchView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_headView.mas_bottom);
        make.left.right.bottom.equalTo(self.view);
    }];
    
    self.searchSuggestion=[[SearchSuggestionView alloc]init];
    self.searchSuggestion.suggestionArray=self.hotArray;
    self.searchSuggestion.searchBlock = ^(NSString *searchTest) {
        [weakSelf pushToSearchResultWithSearchStr:searchTest];
    };
    self.searchSuggestion.packUp = ^() {
        [weakSelf.searchBar resignFirstResponder];
    };
    self.searchSuggestion.hidden = YES;
    [self.view addSubview:self.searchSuggestion];
    [self.searchSuggestion mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_headView.mas_bottom);
        make.left.right.equalTo(self.view);
        make.bottom.equalTo(self.view);
    }];
}
- (UIImage*)searchFieldBackgroundImage {
    
    UIColor*color = [UIColor whiteColor];
    
    CGFloat cornerRadius = 5;
    
    CGRect rect =CGRectMake(0,0,30,30);
    
    UIBezierPath *roundedRect = [UIBezierPath bezierPathWithRoundedRect:rect cornerRadius:cornerRadius];
    
    roundedRect.lineWidth=0;
    
    UIGraphicsBeginImageContextWithOptions(rect.size,NO,0.0f);
    
    [[UIColor grayColor] set];
   
    [color setFill];
    
    [roundedRect fill];
    
    [roundedRect stroke];
    
    [roundedRect addClip];
    
    UIImage *image =UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    
    return image;
    
}

#pragma mark- 热门搜索点击
- (void)pushToSearchResultWithSearchStr:(NSString *)str{
    self.hidesBottomBarWhenPushed=YES;
    [self setHistoryArrWithStr:str];
    SearchResultVC *search=[[SearchResultVC alloc]init];
    [self.navigationController pushViewController:search animated:YES];
    self.searchBar.text=str;
}
#pragma mark- 最近搜索
- (void)setHistoryArrWithStr:(NSString *)str{
    for (int i = 0; i < _historyArray.count; i++) {
        if ([_historyArray[i] isEqualToString:str]) {
            [_historyArray removeObjectAtIndex:i];
            break;
        }
    }
    [_historyArray insertObject:str atIndex:0];
    self.searchView.historyArray=_historyArray;
    [self.searchView reloadSearchHistory];
    
    [NSKeyedArchiver archiveRootObject:_historyArray toFile:KHistorySearchPath];
}
#pragma mark-通过点击button来改变scrollview的偏移量
-(void)adjustScrollView:(NSInteger)index
{
   
}
#pragma mark- 导航栏按钮
-(void)rightBarAction{
    self.hidesBottomBarWhenPushed=YES;
    SearchResultVC *search=[[SearchResultVC alloc]init];
    [self setHistoryArrWithStr:self.searchBar.text];
    [self.navigationController pushViewController:search animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/** 视图即将消失 */
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    // 回收键盘
    [self.searchBar resignFirstResponder];
}



#pragma mark - UISearchBarDelegate -
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    [self pushToSearchResultWithSearchStr:searchBar.text];
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    if (searchBar.text == nil || [searchBar.text length] <= 0) {
       self.searchSuggestion.hidden = YES;
//        [self.view bringSubviewToFront:_searchView];
    } else {
        self.searchSuggestion.hidden = NO;
//        [self.view bringSubviewToFront:_searchSuggestVC.view];
//        [_searchSuggestVC searchTestChangeWithTest:searchBar.text];
    }
}
#pragma mark- get
- (NSMutableArray *)hotArray
{
    if (!_hotArray) {
        self.hotArray = [NSMutableArray arrayWithObjects:@"洗面奶", @"兰芝",@"乳霜",@"乳霜",@"乳霜", @"口红", @"水乳套装", @"防晒霜", @"兰芝", @"口红", @"水乳套装", @"防晒霜", nil];
    }
    return _hotArray;
}
- (NSMutableArray *)historyArray
{
    if (!_historyArray) {
        _historyArray = [NSKeyedUnarchiver unarchiveObjectWithFile:KHistorySearchPath];
        if (!_historyArray) {
            self.historyArray = [NSMutableArray array];
        }
    }
    return _historyArray;
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
